package com.ruoyi.ems.utils;

import com.google.gson.Gson;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.util.Base64;
import java.util.Map;

public class DESUtil {

    private static final String ALGORITHM = "DES";

    private static final Gson gson = new Gson();

    public static String encrypt(Map<String, String> data, String key) throws Exception {
        byte[] keyBytes = key.getBytes();
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        byte[] encryptedBytes = cipher.doFinal(gson.toJson(data).getBytes());

        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static Map<String, String> decrypt(String encryptedData, String key) throws Exception {
        byte[] keyBytes = key.getBytes();
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

        return gson.fromJson(new String(decryptedBytes), Map.class);
    }
}